package zhongbo.java.air.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import zhongbo.java.air.model.FlightPathl;
import zhongbo.java.air.websocet.AlertZoneWebSocket;
import zhongbo.java.air.websocet.PusWebsocket;

import java.util.Date;


@Slf4j
@Component
public class RedisSubscribePusChaneIListener implements MessageListener {
    @Autowired
    private PusWebsocket pusWebsocket;
@Autowired
private AlertZoneWebSocket webSocket;
    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] messageBody = message.getBody();
        String msgString = new String(messageBody);
        log.info("接收到live_flight_path的消息{}", msgString);
        //调用广播数据
        pusWebsocket.broadcastMessage(msgString);
        FlightPathl flightPathl = processMessage(msgString);
        webSocket.selectZone(flightPathl);
    }
    private FlightPathl processMessage(String msgString) {
        JSONObject jsonObject = JSONUtil.parseObj(msgString);
        FlightPathl flightPath = new FlightPathl();

        flightPath.setIcaoCode(jsonObject.getStr("icaoCode"));
        Long timestamp = jsonObject.getLong("timestamp");
        if (timestamp != null) {
            if (timestamp >= 1000L * 365 * 24 * 60 * 60 * 1000 && timestamp <= 9999L * 365 * 24 * 60 * 60 * 1000) {
                Date date = new Date(timestamp);
                flightPath.setTimestamp(date);
            } else {
                Date currentDate = new Date();
                flightPath.setTimestamp(currentDate);
            }
        } else {
            Date currentDate = new Date();
            flightPath.setTimestamp(currentDate);
        }
        flightPath.setLatitude(jsonObject.getDouble("latitude"));
        flightPath.setLongitude(jsonObject.getDouble("longitude"));
        flightPath.setAltitude(jsonObject.getDouble("altitude"));
        flightPath.setSpeed(jsonObject.getDouble("speed"));
        flightPath.setHeading(jsonObject.getDouble("heading"));
        flightPath.setSourceType(jsonObject.getStr("sourceType"));
        return flightPath;
    }
}



